<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NScrollbar,
  NForm,
  NFormItem,
  NSelect,
  NDatePicker,
  NModal,
  NEllipsis,
  useDialog
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch ,onDeactivated} from 'vue'
import { sendRequest } from '@/utils/api'
import type { collectNoticeModel } from '@/api/collectNotice'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import TableView from '@/components/TableView.vue'
import { useRoute, useRouter } from 'vue-router'
const modalVisible = ref(false)
const modalUpVisible = ref(false)
const modalDownVisible = ref(false)
const message = useMessage()
const router = useRouter()
const listOption = ref([])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})
const dialog = useDialog()
const tableData = ref<collectNoticeModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
// const datetime = computed<[string, string]>({
//   get() {
//     return [form.startDate, form.endDate]
//   },
//   set(v) {
//     form.startDate = v[0]
//     form.endDate = v[1]
//   }
// })
const datetime = ref(null)
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    startDate: null,
    endDate: null,
    key: null,
    statusCode: null
  }),
  () => {
    datetime.value = null
    form.startDate = null
    form.endDate = null
    form.key = null
    form.statusCode = null
  }
)
const changeDate = (v: any) => {
  datetime.value = v
  form.startDate = v ? v[0] : null
  form.endDate = v ? v[1] : null
}
const handleAdd = () => {
  router.push({ name: 'CollectionAnnouncementManagementAdd' })
}
const columns: DataTableColumns<collectNoticeModel> = [
  {
    title: '序号',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '5rem',
    align: 'center'
  },
  {
    title: '公告标题',
    key: 'noticeTitle',
    width: '15rem',
    align: 'center'
  },
  {
    title: '公告状态',
    key: 'statusName',
    width: '10rem',
    align: 'center',
    render: (e: any) => {
      return h(
        'div',
        {
          style: {
            color: e.statusCode === 'A3901' ? 'red' : '#000'
          }
        },
        {
          default: () => e.statusName
        }
      )
    }
  },
  {
    title: '开始时间',
    key: 'startDate',
    width: '10rem',
    align: 'center'
  },
  {
    title: '结束时间',
    key: 'endDate',
    width: '10rem',
    align: 'center'
  },
  {
    title: '征集说明',
    key: 'description',
    width: '15rem',
    align: 'center',
    render: (e: any) => {
      return h(
        NEllipsis,
        {
          style: {
            minWidth: '15rem'
          },
          tooltip: {
            contentStyle: {
              maxWidth: '400rem'
            }
          }
        },
        {
          default: () => e.description
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          quaternary: true,
          color: '#06865B',
          style: {
            display: e.statusCode === 'A3901' ? 'none' : 'inline-block'
          },
          onClick: async () => {
            await queryCheckUpdateStatusUp(e.id)
            if (!isDisabled.value) return
            handleUpDelete(e.id)
          }
        },
        {
          default: () => '上架'
        }
      ),
      h(
        NButton,
        {
          quaternary: true,
          color: '#D9534F',
          style: {
            display: e.statusCode === 'A3902' ? 'none' : 'inline-block'
          },
          onClick: async () => {
            handleDownDelete(e.id)
          }
        },
        {
          default: () => '下架'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          // loading: exportLoading.value,
          quaternary: true,
          onClick: () => handleIfo(e)
        },
        {
          default: () => '征集信息'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: async () => {
            await queryEditCheckUpdateStatusUp(e.id)
            if (isEditDisabled.value) {
              handleEdit(e)
            }
          }
        },
        {
          default: () => '修改'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: async () => {
            await queryDelCheckUpdateStatusUp(e.id)
            if (isDelDisabled.value) {
              handleDelete(e.id)
            }
          }
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<collectNoticeModel>>({
    module: 'collectNotice',
    api: 'list',
    override: {
      params: {
        key: form.key,
        statusCode: form.statusCode,
        startDate: form.startDate,
        endDate: form.endDate,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
  tableData.value.forEach((e) => {
    e.description = e.description.replace(/<[^>]+>/g, '').replace(/&nbsp;/gi, '')
  })
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A39'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const isAdd = ref(false)
const queryCheckUserInZjb = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUserInZjb'
  })
  if (error) return message.error(error.message)
  isAdd.value = res.data
}
const handleEdit = (e: any) => {
  router.push({ name: 'CollectionAnnouncementManagementEditList', params: { id: e.id } })
}
const handleDetail = (e: any) => {
  router.push({ name: 'CollectionAnnouncementManagementDetailList', params: { id: e.id } })
}
const handleIfo = (e: any) => {
  router.push({ name: 'informationSolicitation', params: { noticeId: e.id } })
}
const ids = ref()
const handleDelete = async (id: any) => {
  ids.value = id
  modalVisible.value = true
}
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'delete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalVisible.value = false
}
const idsUp = ref()
const handleUpDelete = async (id: any) => {
  idsUp.value = id
  modalUpVisible.value = true
}
const againHandleUpDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'updateStatusUp',
    override: {
      data: {
        id: idsUp.value
      }
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalUpVisible.value = false
}
const idsDown = ref()
const handleDownDelete = async (id: any) => {
  idsDown.value = id
  modalDownVisible.value = true
}
const againHandleDownDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'updateStatusDown',
    override: {
      data: {
        id: idsDown.value
      }
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalDownVisible.value = false
}
//上架校验
const isDisabled = ref(false)
const queryCheckUpdateStatusUp = async (id: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUpdateStatusUp',
    override: {
      params: {
        id
      }
    }
  })
  if (error) return message.error(error.message)
  isDisabled.value = res.data.nextOperateFlag
  if (!res.data.nextOperateFlag) return message.error(res.data.message)
}
//删除校验
const isDelDisabled = ref(false)
const queryDelCheckUpdateStatusUp = async (id: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkDelete',
    override: {
      params: {
        id
      }
    }
  })
  if (error) return message.error(error.message)
  isDelDisabled.value = res.data.nextOperateFlag
  if (!res.data.nextOperateFlag) return message.error(res.data.message)
}
//修改校验
const isEditDisabled = ref(false)
const queryEditCheckUpdateStatusUp = async (id: any) => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'checkUpdate',
    override: {
      params: {
        id
      }
    }
  })
  if (error) return message.error(error.message)
  isEditDisabled.value = res.data.nextOperateFlag
  if (!res.data.nextOperateFlag) return message.error(res.data.message)
}
const reminderVisible = ref(false)
const reminderContent = ref()
// 弹窗提醒需要处理事项
const getReminderInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'collectNotice',
    api: 'getCollectNoticePopUpReminderInfo'
  })
  if (error) return
  if (res.code != 0) return
  if (res.data?.[0].popUpFlag) reminderVisible.value = true
  reminderContent.value = res.data?.[0].content
}

onMounted(() => {
  getReminderInfo()
  getFunction()
  queryCheckUserInZjb()
  queryTableData(true)
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (
      route.path == '/collectionManagement/collectionProcess/collectionAnnouncementManagement/index'
    ) {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="公告标题:">
            <NInput
              placeholder="输入公告标题"
              v-model:value="form.key"
            />
          </NFormItem>
          <NFormItem label="公告状态:">
            <NSelect
              :options="listOption"
              v-model:value="form.statusCode"
              placeholder="请选择公告状态"
              clearable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="日期范围:">
            <NDatePicker
              input-readonly
              v-model:formatted-value="datetime"
              value-format="yyyy-MM-dd"
              type="daterange"
              @update:formatted-value="changeDate"
              clearable
            />
          </NFormItem>
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px; margin-right: 10px"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              type="primary"
              ghost
              style="width: 78px"
              @click="resetForm"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
            v-if="isAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
      />
    </template>
    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
  <NModal
    :auto-focus="false"
    v-model:show="modalUpVisible"
  >
    <VDialogContent
      @close="modalUpVisible = false"
      @submit="againHandleUpDelete"
      title="上架提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        是否上架当前公告？
      </div>
    </VDialogContent>
  </NModal>
  <NModal
    :auto-focus="false"
    v-model:show="modalDownVisible"
  >
    <VDialogContent
      @close="modalDownVisible = false"
      @submit="againHandleDownDelete"
      title="下架提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        是否下架当前公告？
      </div>
    </VDialogContent>
  </NModal>
  <NModal  v-model:show="reminderVisible">
    <VDialogContent
      @close="reminderVisible = false"
      title="提示"
      :submitVisible ="false"
      closeText = "关闭"
    >

      <NScrollbar style="width: 300rem; height: 100rem; text-align: center;">
       {{ reminderContent }}
      </NScrollbar>
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
